package cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.controller;

import cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.entity.Inventory;
import cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.service.InventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/inventory/cached")
@Slf4j
public class InventoryCacheController {

    private InventoryService inventoryService;

    @Autowired
    public void setInventoryService(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    /**
     * 定向请求
     * <ol>
     *     <li>先从redis中查询</li>
     *     <li>如果redis中查询不到，则从数据库中查询</li>
     * </ol>
     */
    @GetMapping("/{id}")
    public Inventory cache(@PathVariable("id") String id) {
        Inventory inventory = this.inventoryService.getCache(id);
        if (inventory == null) {
            log.info("---> 缓存未命中，从数据库中获取");
            inventory = inventoryService.selectById(id);
        }
        return inventory;
    }
}
